package be.fomp.jeve.application.data.standard.errorlist;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;

import be.fomp.jeve.application.data.AbstractResultImpl;
import be.fomp.jeve.application.data.standard.ErrorList;
import be.fomp.jeve.core.exceptions.JEveException;

public final class ErrorListImpl extends AbstractResultImpl implements ErrorList{
	static final long serialVersionUID = 1L;
	
	private Map<Integer, String> errors = new HashMap<Integer, String>();
	
	@SuppressWarnings("unchecked")
	public ErrorListImpl(Document xmlDocument) throws JEveException{
		super(xmlDocument);
		
		Element root = xmlDocument.getRootElement();
		
		List<Element> resultSet = root.getChild("result").getChild("rowset").getChildren();
		for(Element errorElement: resultSet){
			Integer errorCode = Integer.valueOf(errorElement.getAttributeValue("errorCode"));
			String errorText = errorElement.getAttributeValue("errorText");
			
			this.errors.put(errorCode, errorText);
		}
	}
	
	public Map<Integer, String> getErrors()	{
		return this.errors;
	}
	
	public String getErrorByCode(int errorCode)	{
		return this.errors.get(errorCode);
	}
	
	public void writeObject(ObjectOutputStream os) {
		try {
			os.defaultWriteObject();
			os.writeObject(this.errors);
		} catch (Exception e) { e.printStackTrace();  }
	}

	@SuppressWarnings("unchecked")
	public void readObject (ObjectInputStream is) {
		try {
			is.defaultReadObject();
			this.errors = ((Map<Integer, String>)is.readObject());
		} catch (Exception e) {e.printStackTrace();}
	}
}
